package yxxy.c_019.Semaphore;


import java.text.SimpleDateFormat;
import java.util.concurrent.*;

/**
 * 以下是非公平信号量Semaphore
 * 非公平模式是抢占式的，也就是有可能一个新的获取线程恰好在一个许可证释放时得到了这个许可证，而前面还有等待的线程
 */

@SuppressWarnings("all")
public class SemaphoreExample1 {
    private static final Semaphore semaphore=new Semaphore(2,true);
    private static final ThreadPoolExecutor threadPool=new ThreadPoolExecutor(5,10,60,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>());

    private static class InformationThread extends Thread{
        private final String name;
        private final int age;
        public InformationThread(String name,int age)
        {
            this.name=name;
            this.age=age;
        }

        public void run()
        {
            try
            {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Thread.sleep(5000);
                semaphore.acquire();
                System.out.println(Thread.currentThread().getName()+":大家好，我是"+name+"我今年"+age+"岁当前时间为："+   sdf.format(System.currentTimeMillis()));
                Thread.sleep(1000);
                System.out.println(name+"要准备释放许可证了，当前时间为："+   sdf.format(System.currentTimeMillis()));
                System.out.println("当前可使用的许可数为："+semaphore.availablePermits());
                semaphore.release();

            }
            catch(InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        System.out.println("初始许可证数为："+semaphore.availablePermits());
        String[] name= {"陈奕迅","华晨宇","张碧晨","林俊杰"};
        int[] age= {26,27,33,45};
        for(int i=0;i<4;i++)
        {
            Thread t1=new InformationThread(name[i],age[i]);
            threadPool.execute(t1);
        }
        System.out.println("关闭前许可证数为："+semaphore.availablePermits());
            threadPool.shutdown();
    }
}
